import { defineStore } from 'pinia'
import { request } from '@/utils/request'

export const useTagStore = defineStore('tags', {
  state: () => ({
    tags: [],
    loading: false
  }),

  actions: {
    async fetchTags() {
      this.loading = true
      try {
        const { data } = await request.get('/tags')
        this.tags = data
      } catch (error) {
        console.error('获取标签列表失败:', error)
        throw error
      } finally {
        this.loading = false
      }
    },

    async createTag(tag) {
      try {
        const { data } = await request.post('/tags', tag)
        this.tags.push(data)
        return data
      } catch (error) {
        console.error('创建标签失败:', error)
        throw error
      }
    },

    async updateTag(tag) {
      try {
        const { data } = await request.put(`/tags/${tag.id}`, tag)
        const index = this.tags.findIndex(item => item.id === tag.id)
        if (index !== -1) {
          this.tags[index] = data
        }
      } catch (error) {
        console.error('更新标签失败:', error)
        throw error
      }
    },

    async deleteTag(tagId) {
      try {
        await request.delete(`/tags/${tagId}`)
        this.tags = this.tags.filter(tag => tag.id !== tagId)
      } catch (error) {
        console.error('删除标签失败:', error)
        throw error
      }
    }
  }
})